package com.lening.community.service.impl;

import com.lening.community.service.BuildingService;
import com.lening.community.service.CommunityService;
import com.lening.community.service.HouseService;
import com.lening.community.service.UnitService;
import com.lening.community.vo.TableVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @ToDo:
 * @Author：潘万法
 * @date: 2024/6/13 8:31
 */
@Slf4j
@Service
public class Comm {
    @Autowired(required = false)
    private CommunityService communityService;
    @Autowired(required = false)
    private BuildingService buildingService;
    @Autowired(required = false)
    private HouseService houseService;
    @Autowired(required = false)
    private UnitService unitService;

    /**
     * 多线程查询
     * @return
     */

    public List<TableVo> execute() {
        //自定义线程池
        ExecutorService executorService = Executors.newFixedThreadPool(4); // 设并发执行4个任务

        CompletableFuture<List<TableVo>> cyFuture = CompletableFuture.supplyAsync(() -> communityService.getAllComm(), executorService);
        CompletableFuture<List<TableVo>> bdFuture = CompletableFuture.supplyAsync(() -> buildingService.getAllBui(), executorService);
        CompletableFuture<List<TableVo>> utFuture = CompletableFuture.supplyAsync(() -> unitService.getAllUnit(), executorService);
        CompletableFuture<List<TableVo>> heFuture = CompletableFuture.supplyAsync(() -> houseService.getAllHouse(), executorService);

        CompletableFuture.allOf(cyFuture, bdFuture, utFuture, heFuture).join();

        List<TableVo> list = new ArrayList<>();

        try {
            //当使用 get() 方法从 CompletableFuture 中获取结果时，如果任务尚未完成，get() 方法会阻塞当前线程，直到任务完成,调用get方法需要等待异步任务完成的。
            List<TableVo> cyList = cyFuture.get();
            List<TableVo> bdList = bdFuture.get();
            List<TableVo> utList = utFuture.get();
            List<TableVo> heList = heFuture.get();

            list.addAll(cyList);
            list.addAll(bdList);
            list.addAll(utList);
            list.addAll(heList);

        } catch (InterruptedException | ExecutionException e) {
            // 清理资源（如关闭线程池）并重新抛出异常
            throw new RuntimeException(e);
        } finally {
            // 始终关闭线程池  ,避免资源泄露
            executorService.shutdown();
        }

        return list;
    }

    public List<TableVo> getAll() {

        List<TableVo> execute = this.execute();
//        //封装树形数据
        Map<Long, List<TableVo>> groupMap = execute.stream().filter(item->item.getZid()!=null).collect(Collectors.groupingBy(TableVo::getZid));
        log.info("collect:{}", groupMap);
        execute.forEach(item -> {
            item.setChildren(groupMap.get(item.getId()));
        });

        //过滤返回数据
        return execute.stream().filter(item->item.getZid()!=null).filter(item -> item.getZid() == -1L).collect(Collectors.toList());
        //封装树形数据
//        Map<Long, List<TableVo>> groupByMap = execute.stream().filter(item -> item.getZid() != null).collect(Collectors.groupingBy(TableVo::getZid));
//        execute.forEach(item -> item.setChildren(groupByMap.get(item.getId())));
//
//        //过滤返回数据
//        return execute.stream().filter(item -> item.getZid() != null).filter(item -> item.getZid() == -1).collect(Collectors.toList());

//        return execute;


    }
}

